from fastapi import FastAPI, WebSocket, WebSocketDisconnect
from fastapi.staticfiles import StaticFiles
from fastapi.responses import FileResponse
import uvicorn
from websocket_handler import WebSocketHandler
from game_room import GameRoom

app = FastAPI(title="Texas Hold'em Poker")

# 全局游戏房间（单房间模式）
game_room = GameRoom()
websocket_handler = WebSocketHandler(game_room)

# 静态文件服务
app.mount("/static", StaticFiles(directory="static"), name="static")


@app.websocket("/ws")
async def websocket_endpoint(websocket: WebSocket):
    await websocket.accept()
    print(f"WebSocket连接建立: {websocket.client}")

    try:
        # 将连接添加到处理器
        await websocket_handler.add_connection(websocket)

        # 监听消息
        while True:
            data = await websocket.receive_json()
            await websocket_handler.handle_message(websocket, data)

    except WebSocketDisconnect:
        print(f"WebSocket连接断开: {websocket.client}")
        await websocket_handler.remove_connection(websocket)
    except Exception as e:
        print(f"WebSocket错误: {e}")
        await websocket_handler.remove_connection(websocket)


@app.get("/")
async def get_index():
    """返回主页"""
    return FileResponse("static/index.html")


@app.get("/api/room/status")
async def get_room_status():
    """获取房间状态API"""
    room_state_data = await game_room.get_room_state()
    return {
        "success": True,
        "data": room_state_data
    }


@app.get("/health")
async def health_check():
    return {
        "status": "ok",
        "room_state": game_room.room_state.value,
        "players_count": len(game_room.human_players),
        "total_players": game_room.total_players
    }


if __name__ == "__main__":
    print("启动德州扑克服务器...")
    print("WebSocket地址: ws://localhost:8000/ws")
    print("游戏地址: http://localhost:8000")
    uvicorn.run(app, host="0.0.0.0", port=8000)